package cn.stylefeng.guns.modular.basic.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.json.JSONObject;
import cn.stylefeng.guns.modular.basic.model.result.BasicDriverResult;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStorageStockParam;
import cn.stylefeng.guns.modular.hx.storage.model.result.HxStorageStockResult;
import cn.stylefeng.guns.modular.order.entity.OrderPut;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.CangGuanRoleId;
import cn.stylefeng.guns.core.util.QRCodeUtil;
import cn.stylefeng.guns.modular.basic.entity.BasicDriver;
import cn.stylefeng.guns.modular.basic.entity.BasicOperate;
import cn.stylefeng.guns.modular.basic.model.params.BasicDriverParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicOilCardParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicOperateParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicOperateResult;
import cn.stylefeng.guns.modular.basic.service.BasicDriverService;
import cn.stylefeng.guns.modular.basic.service.BasicOilCardService;
import cn.stylefeng.guns.modular.basic.service.BasicOperateService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.model.UserDto;
import cn.stylefeng.guns.sys.modular.system.service.FileInfoService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;

/**
 * 驾驶员信息表控制器
 */
@Controller
@RequestMapping("/basicDriver")
public class BasicDriverController extends BaseController {

    private String PREFIX = "/basic/basicDriver";

    @Autowired
    private BasicDriverService basicDriverService;

    @Autowired
    private UserService userService;

    @Autowired
    private BasicOperateService basicOperateService;

    @Autowired
    private BasicOilCardService basicOilCardService;

    @Autowired
    private FileInfoService fileInfoService;

    /**
     * 跳转到主页面
     */
    @RequestMapping("")
    public String index(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	
    	//查询可选择分公司
    	model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/basicDriver.html";
    }

    @RequestMapping("/toqrCode")
    public String toqrCode(BasicDriverParam basicDriverParam) {
        return PREFIX + "/qrCode.html";
    }

    /**
     * 创建二维码
     */	
    @RequestMapping(value = "/getqrcode", method = RequestMethod.GET)
    @ResponseBody
    public void generateQRCode4Product(Integer id,String name, HttpServletRequest request, HttpServletResponse response) {
    	User user = userService.getcurrentUser();
    	BasicOperateParam param = new BasicOperateParam();
    	param.setDeptId(user.getDeptId());
    	BasicOperateResult basicOperateResult = basicOperateService.findBySpec(param,user.getOperateId());
    	if(basicOperateResult != null) {
    		id = basicOperateResult.getId();
    		try {
    			//logo
    			File logoFile = new File("");
    			
    			String url = "https://jilu56it.top//register?operateId="+id;
    			
    			QRCodeUtil.drawLogoQRCode(logoFile, url, name,350,350,request,response);
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }

    /**
     * layui上传组件 通用文件上传接口
     *
     * @author fengshuonan
     * @Date 2019-2-23 10:48:29
     */
    @RequestMapping(method = RequestMethod.POST, path = "/upload")
    @ResponseBody
    public ResponseData layuiUpload(@RequestPart("file") MultipartFile file) {

        String fileId = this.fileInfoService.uploadFileCar(file);

        HashMap<String, Object> map = new HashMap<>();
        map.put("fileId", fileId);

        return ResponseData.success(0, "Upload Successful", map);
    }

    /**
     * 新增页面
     */
    @RequestMapping("/add")
    public String add(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	
    	//查询可选择分公司
    	model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId,deliverId,user.getOperateId()));
    	//查询可选择油卡
    	BasicOilCardParam basicOilCardParam = new BasicOilCardParam();
    	basicOilCardParam.setDeliverId(deliverId);
    	model.addAttribute("basicOilCardlist", basicOilCardService.findListBySpec(basicOilCardParam,user.getOperateId()));
        return PREFIX + "/basicDriver_add.html";
    }

    /**
     * 编辑页面
     */
    @RequestMapping("/edit")
    public String edit(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	
    	//查询可选择分公司
    	model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId,deliverId,user.getOperateId()));
    	//查询可选择油卡
    	BasicOilCardParam basicOilCardParam = new BasicOilCardParam();
    	basicOilCardParam.setDeliverId(deliverId);
    	model.addAttribute("basicOilCardlist", basicOilCardService.findListBySpec(basicOilCardParam,user.getOperateId()));
        return PREFIX + "/basicDriver_edit.html";
    }

    /**
     * 导入页面
     */
    @RequestMapping("/toimportExcel")
    public String toimportExcel(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	
    	//查询可选择分公司
    	model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/import.html";
    }
    
    /**
     * 下载模板
     * @throws ServletException , IOException
     */
    @RequestMapping("downloadExcel")
    public void downloadExcel(HttpServletRequest request,HttpServletResponse response) throws ServletException ,IOException {
        String path = "assets/excel/driver.xlsx";
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
            OutputStream  outputStream = response.getOutputStream();
            //设置下载的文件类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置下载文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("Driver Template" + ".xlsx").getBytes(), "iso-8859-1"));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 下载模板
     * @throws ServletException , IOException
     */
    @RequestMapping("downloadExcel2")
    public void downloadExcel2(HttpServletRequest request,HttpServletResponse response) throws ServletException ,IOException {
        String path = "assets/excel/user.xlsx";
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
            OutputStream  outputStream = response.getOutputStream();
            //设置下载的文件类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置下载文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("User Template" + ".xlsx").getBytes(), "iso-8859-1"));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入excel   
     */
	@RequestMapping(value = "/importExcel" , method = {RequestMethod.POST} )
    @ResponseBody
    public ResponseData importExceNewmethodl(@RequestPart("file") MultipartFile file,  BasicDriverParam basicDriverParam)  {
		ResponseData data = new ResponseData();
		try {
			data = basicDriverService.getExceldata(file,basicDriverParam,data);//处理导入数据
		} catch (Exception e) {
			data.setSuccess(false);
			e.printStackTrace();
		}
        return data;
    }

    /**
     * 导入User excel   
     */
	@RequestMapping(value = "/importExcel2" , method = {RequestMethod.POST} )
    @ResponseBody
    public ResponseData importExceNewmethodl2(@RequestPart("file") MultipartFile file,  UserDto user)  {
		ResponseData data = new ResponseData();
		try {
			data = basicDriverService.getExceldata2(file,user,data);//处理导入数据
		} catch (Exception e) {
			data.setSuccess(false);
			e.printStackTrace();
		}
        return data;
    }

    /**
     * 新增接口
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(BasicDriverParam basicDriverParam) {
    	User user = userService.getByAccount(basicDriverParam.getDriverNumber());
    	if(user != null) {
    		return ResponseData.error("This account has already been registered");
    	}
        Object driverOperateId = basicDriverParam.getDriverOperateId();
        if (driverOperateId != null) {
            BasicOperate Operate = basicOperateService.getById(Integer.parseInt(driverOperateId.toString()));
            basicDriverParam.setDriverOperateName(Operate.getOperateName());
        }
        User meuser = userService.getcurrentUser();
        //set 交付id
        Long DeliverId = meuser.getDeliverId();
        if (DeliverId!=null) {
            basicDriverParam.setDeliverId(DeliverId);
        }
        basicDriverParam.setDeptId(meuser.getDeptId());
        //添加账号
        UserDto userDto = new UserDto();
        userDto.setAccount(basicDriverParam.getDriverNumber());
        userDto.setPassword("111111");
        userDto.setName(basicDriverParam.getDriverName());
        userDto.setSex("M");
        userDto.setPhone(basicDriverParam.getTel());
        userDto.setRoleId(CangGuanRoleId.SJRoleId.toString());
        userDto.setDeptId(meuser.getDeptId());
        userDto.setStatus("ENABLE");
        userDto.setDeliverId(DeliverId);
        userDto.setDeliverName(userService.getdeliverName());
        userDto.setOperateId(meuser.getOperateId());
        userService.addUser(userDto);
        user = userService.getByAccount(basicDriverParam.getDriverNumber());
        basicDriverParam.setUserId(user.getUserId());
        this.basicDriverService.add(basicDriverParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(BasicDriverParam basicDriverParam) {
        Object driverOperateId = basicDriverParam.getDriverOperateId();
        if (driverOperateId != null) {
            BasicOperate Operate = basicOperateService.getById(Integer.parseInt(driverOperateId.toString()));
            basicDriverParam.setDriverOperateName(Operate.getOperateName());
        }
        
        BasicDriver basicDriver = basicDriverService.getById(basicDriverParam.getId());
        if(!basicDriver.getDriverName().equals(basicDriverParam.getDriverName()) || !basicDriver.getDriverNumber().equals(basicDriverParam.getDriverNumber())|| !basicDriver.getTel().equals(basicDriverParam.getTel())) {
        	User user = userService.getByAccount(basicDriver.getDriverNumber());
        	if(user != null) {
            	if(!basicDriver.getDriverNumber().equals(basicDriverParam.getDriverNumber())) {
                	User user2 = userService.getByAccount(basicDriverParam.getDriverNumber());
                	if(user2 != null) {
                		return ResponseData.error("This account has already been registered");
                	} else {
                		user.setName(basicDriverParam.getDriverName());
                		user.setAccount(basicDriverParam.getDriverNumber());
                		user.setPhone(basicDriverParam.getTel());
                		userService.updateById(user);
                	}
            	} else {
            		user.setName(basicDriverParam.getDriverName());
            		user.setPhone(basicDriverParam.getTel());
            		userService.updateById(user);
            	}
        	}
        }
        
        this.basicDriverService.update(basicDriverParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(BasicDriverParam basicDriverParam) {
        this.basicDriverService.delete(basicDriverParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(BasicDriverParam basicDriverParam) {
        BasicDriver detail = this.basicDriverService.getById(basicDriverParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(BasicDriverParam basicDriverParam,String condition ) {
    	User user = userService.getcurrentUser();
        basicDriverParam.setDeliverId(user.getDeliverId());
        // 默认部门
        basicDriverParam.setDeptId(user.getDeptId());
        return this.basicDriverService.findPageBySpec(basicDriverParam,condition,user.getOperateId());
    }

    /**
     *         post = HttpRequest.post(url)
     *         .header("Authorization", "bearer " + oauth2tokenResult.getOauth2TokenXlb()).body(json.toString()).execute().body();
     */
    @RequestMapping("/synchronization")
    @ResponseBody
    public ResponseData synchronization(Integer[] ids) {
         if (ids == null || ids.length == 0) {
            return ResponseData.error("Required ID not provided");
        }
        try {
            for (Integer id : ids) {
                BasicDriver basicDriver = basicDriverService.getById(id);
                if (basicDriver == null) {
                    return ResponseData.error("Not found" + id);
                }
                BasicDriverParam basicDriverParam = new BasicDriverParam();
                basicDriverParam.setId(basicDriver.getId());
                //BasicDriverResult stockResult = basicDriverService.synchronization(basicDriverParam);

            }
        } catch (Exception e) {
            return ResponseData.error("Synchronization Failed" + e.getMessage());
        }
        return ResponseData.success();
    }

    public static void main(String[] args) {
        JSONObject json2 = new JSONObject();
        json2.put("real_name","");
        json2.put("sdds","");

        JSONObject json1 = new JSONObject();
        json1.put("syncDriverAndCarReqDTO",json2);
        System.out.println(json1.toString());

    }

}